package com.mti.jwt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Optional;
import java.util.Set;

/**
 * <p>
 *
 * </p>
 *
 * @author yangsp
 * @since 2019-04-29
 */
@Component
@Slf4j
public class RequestUtils {

	@Autowired
	private StringRedisTemplate redisTemplate;

	/**
	 * 用户登录后从redis获取用户信息
	 * @return
	 */
	public AccountBo getCurrentUser(ServerWebExchange serverWebExchange){
		ServerHttpRequest request=  serverWebExchange.getRequest();
		String token = request.getHeaders().getFirst(JwtTokenFactory.HEADER_STRING);
		System.out.println("token==>"+token);
		log.info("token==>{}",token);
		if(StringUtils.isEmpty(token))
			return null;
        Set<String> keys = redisTemplate.keys( "*" + token);
        String authorization = null;
        if (keys==null || keys.isEmpty()) {
            return null;
//            throw new BusinessException(HttpStatus.SC_UNAUTHORIZED, "不合法的请求，请验证是否登陆");
        }
        log.info("keys.size===>{}",keys.size());
        for(String str : keys) {
//            account = JSON.parseObject((String)redisTemplate.opsForValue().get(str), AccountBo.class ) ;
            authorization = redisTemplate.opsForValue().get(str);
        }
        if (org.apache.commons.lang3.StringUtils.isEmpty(authorization)) {
            return null;
//            throw new BusinessException(HttpStatus.SC_UNAUTHORIZED, "用户未登录或者已经过期");
        }
        System.out.println("authorization===>" + authorization);
		AccountBo account = JSON.parseObject(authorization, AccountBo.class ) ;
		if (null == account) {
			log.info("===>account.parse is null");
            return null;
//		    throw new BusinessException(HttpStatus.SC_UNAUTHORIZED, "用户未登录或者已经过期");
		}
		return account;
	}
	/**
	 * 根据用户名获取
	 * @return
	 */
	public AccountBo getUser(String loginName){
		if(StringUtils.isEmpty(loginName))
			return null;
		String json = Optional.ofNullable(redisTemplate.opsForHash().get("LOGIN_NAME_BO", loginName)).orElse("").toString();
		AccountBo account = JSON.parseObject(json, AccountBo.class ) ;
		if (null == account) {
			log.error("缓存中没有获取到用户信息");
		}
		return account;
	}
	/**
	 * 获取IP
	 * @return
	 */
//	public  String getCurrentIp(){
//		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
//		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
//		HttpServletRequest request = sra.getRequest();
//		String ip = request.getHeader("X-Forwarded-For");
//		Enumeration<String> headers = request.getHeaderNames();
//		String h = "";
//		while(headers.hasMoreElements()) {
//			h = headers.nextElement();
//			Enumeration<String> result = request.getHeaders(h);
//			System.out.println(h+" :"+ request.getHeaders(h));
//			while(result.hasMoreElements()) {
//				System.out.println(result.nextElement());
//			}
//		}
//
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getHeader("Proxy-Client-IP");
//		}
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getHeader("WL-Proxy-Client-IP");
//		}
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getHeader("HTTP_CLIENT_IP");
//		}
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//		}
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getRemoteAddr();
//		}
//		return ip;
//	}


//	/**
//	 * 获取访问url
//	 * @return
//	 */
//	public  String getRequestURI(){
//		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
//		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
//		HttpServletRequest request = sra.getRequest();
//		return request.getRequestURI();
//
//	}

}
